<template>
  <view class="gift-detail" :class="[isIpx ? 'fix-iphonex-button' : '']">
    <loading :showLoaded.sync="showLoaded"></loading>
    <navBar :navbarData.sync="navbarData"></navBar>
    <view class="gift-container">
      <view
        class="kv-box"
        :style="{ height: vheight + 'px', overflow: 'hidden' }"
      >
        <image
          :src="giftInfo.imgUrlDetail[0]"
          style="width: 750rpx"
          mode="widthFix"
        />
      </view>
      <!--      <view class="gift-info">{{giftInfo.giftName}}</view> -->
      <view class="activity_date">
        <view class="title">领取时间</view>
        <view class="text">
          {{ formatDate(giftInfo.fromDate) }}-{{ formatDate(giftInfo.toDate) }}
        </view>
      </view>

      <view class="gift-intro" v-if="giftInfo.description">
        <view class="title">礼遇介绍</view>
        <view class="text">
          {{ giftInfo.description }}
        </view>
      </view>

      <image
        :src="giftInfo.imgUrlDetail[1]"
        style="width: 750rpx; margin-top: 96rpx"
        mode="widthFix"
      />

      <view class="gift-notice" v-if="giftInfo.attention">
        <view class="title">注意事项</view>
        <view class="text">{{ giftInfo.attention }}</view>
      </view>
      <view class="gift-button">
        <view class="btn-tip">{{ buttonTip }}</view>
        <img
          src="https://100000063-1252208446.file.myqcloud.com/images/MF-EB-P4/activity/divider@2x.png"
          style="width: 750rpx"
          mode="widthFix"
        />
        <view
          class="btn-text"
          @click="handle(buttonText)"
          :class="buttonText == '礼遇已领完' ? 'grey' : ''"
        >
          {{ buttonText }}
        </view>
      </view>
      <!-- <view class="gift-button" :class="[isIpx ? 'fix-iphonex-button' : '']">
        <view class="btn-tip">{{buttonTip}}</view>
        <view class="btn-text" @click="handle(buttonText)" :class="buttonText =='礼遇已领完'?'grey':'' ">{{buttonText}}
        </view>
      </view> -->
    </view>
    <view
      class="mask-box-2"
      v-if="isGetGiftTrue"
      @click.stop="isGetGiftTrue = false"
      @touchmove.stop.prevent
      catchtouchmove="true"
    >
      <view
        class="params-padding-box-3"
        :style="{ bottom: isIpx ? '414rpx' : '350rpx' }"
        @click.stop="stopClick"
      >
        <image
          style="width: 654rpx; height: 728rpx"
          mode="widthFix"
          src="https://100000063-1252208446.file.myqcloud.com/images/MF-EB-P4/activity/giftTip.png"
          alt=""
        />
        <image
          :src="giftInfo.imgUrl"
          style="
            position: absolute;
            top: 300rpx;
            right: 231rpx;
            width: 192rpx;
            height: 192rpx;
          "
          mode="widthFix"
          alt=""
        />
        <view
          @click.stop="isGetGiftTrue = false"
          style="
            position: absolute;
            top: 15rpx;
            right: 14rpx;
            width: 90rpx;
            height: 90rpx;
          "
        ></view>

        <view
          @click="handle2('查看礼遇')"
          style="
            position: absolute;
            left: 52rpx;
            top: 550rpx;
            width: 550rpx;
            height: 100rpx;
          "
        ></view>
      </view>
    </view>
		<!-- 弱提示 弹窗 -->
		<toast-popup ref="toastPopup" @onToastPopupClick="onToastPopupClick"></toast-popup>
  </view>
</template>

<script>
import api from "@/api/api";
import NavBar from "@/components/common/navbar";
import Loading from "@/components/common/loading";
import {
  SYSTEM_INFO,
  USER_INFO,
  CUSTOMER_INFO,
  MERCHANT_INFO,
} from "@/utils/constant";
export default {
  components: {
    navBar: NavBar,
    loading: Loading,
  },
  data() {
    return {
      navbarData: {
        showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
        navbarTitle: "", //导航栏 中间的标题
        isTopFixed: false,
        newLogo: uni.getStorageInfoSync("storeLogo"),
        hideHome: true,
      },
      swiperArr: [
        {
          url: "https://100000063-1252208446.file.myqcloud.com/images/pdp_hb_01.jpg",
        },
        {
          url: "https://100000063-1252208446.file.myqcloud.com/images/pdp_hb_01.jpg",
        },
      ],
      giftInfo: {},
      buttonTip: "数量有限，领完即止",
      buttonText: "即刻申领",
      showLoaded: true,
      stock: "",
      recordId: "",
      activityId: "",
      circular: true,
      currentIndex: 0,
      isIpx: false,
      vheight: "",
      isGetGiftTrue: false,
      ruleBoxData: {
        title:
          "https://100000063-1252208446.file.myqcloud.com/images/MF-EB-P4/tsRule/tsRule_01.png",
        list: [
          "https://100000063-1252208446.file.myqcloud.com/images/MF-EB-P4/tsRule/tsRule_02_01.png",
          "https://100000063-1252208446.file.myqcloud.com/images/MF-EB-P4/tsRule/tsRule_02_02.png",
          "https://100000063-1252208446.file.myqcloud.com/images/MF-EB-P4/tsRule/tsRule_02_03.png",
          "https://100000063-1252208446.file.myqcloud.com/images/MF-EB-P4/tsRule/tsRule_02_04.png",
        ],
      },
    };
  },
  onLoad(options) {
    const { id, isGetGiftTrue = false } = options;
    this.activityId = id;
    this.isGetGiftTrue = isGetGiftTrue;
    let systemInfo = uni.getSystemInfoSync();
    this.isIpx =
      systemInfo.system.includes("iOS") && systemInfo?.safeArea?.top > 20;
    let rect = uni.getMenuButtonBoundingClientRect
      ? uni.getMenuButtonBoundingClientRect()
      : null; //胶囊按钮位置信息
    let pixelRatio1 = 750 / systemInfo.windowWidth;
    let navBarHeight = (function () {
      //导航栏高度
      let gap = rect.top - systemInfo.statusBarHeight; //动态计算每台手机状态栏到胶囊按钮间距
      return 2 * gap + rect.height;
    })();

    this.vheight =
      systemInfo.windowHeight - navBarHeight - systemInfo.statusBarHeight;
  },
 async onShow(options) {
    await this.getGiftStatus();
	setTimeout(()=>{
		const params={
			page_name:'礼品详情',
			gift_name: this.giftInfo?.giftName || '',
		}
		this.$commonSensors.giftsDetailTrack('GiftsDetailPageView',params);
	},8000)
  },
  methods: {
		/**
		 * 展示弱提示
		 * @param {Object} msg 文案
		 */
		handleShowTextToast(msg){
			try{
				this.$refs.toastPopup.showToast(msg);
			}catch(e){}
		},
		/**
		 * 若提示按钮点击回调
		 * @param {Object} data.type 类型：confirm确定，cancel取消
		 * @param {Object} data.callBackData 呼气弹窗时传入的数据
		 */
		onToastPopupClick(data){},
    async getGiftStatus() {
      let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
      const res = await api.getGiftStatus(
        {
          header: {
            jwt: customerInfo.jwt,
          },
        },
        this.activityId
      );
      if (res.code === 1000) {
        // 没有申请
        if (res.data.isReceived == "No") {
          this.getGiftStock();
        } else {
          await  this.getGiftDetail(true);
          this.buttonText = "查看礼遇";
          this.buttonTip = "您已成功领取本次礼遇";
          this.recordId = res.data.recordId;
        }
      }
    },
	stopClick(){},
    async getGiftStock() {
      let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
      const res = await api.getGiftStock(
        {
          header: {
            jwt: customerInfo.jwt,
          },
        },
        this.activityId
      );
      if (res.code === 1000) {
        // 没有申请
        this.stock = res.data.stock;
        if (this.stock <= 0) {
          this.buttonText = "礼遇已领完";
          this.buttonTip = "期待您下次参与";
        } else {
          this.buttonTip = "数量有限，领完即止";
          this.buttonText = "即刻申领";
        }
         await this.getGiftDetail();
      }
    },
    async getGiftStock2() {
      let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
      const res = await api.getGiftStock(
        {
          header: {
            jwt: customerInfo.jwt,
          },
        },
        this.activityId
      );
      if (res.code === 1000) {
        // 没有申请
        this.stock = res.data.stock;
        if (this.stock <= 0) {
          return false;
        } else {
          return true;
        }
      }
    },
    async getGiftDetail(flag) {
      let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
      const res = await api.getGiftDetail(
        {
          header: {
            jwt: customerInfo.jwt,
          },
        },
        this.activityId
      );
      if (res.code === 1000) {
		  this.giftInfo = res.data;
        let nowTime = new Date().getTime();
        let toDate = res.data.toDate;
        toDate = new Date(toDate.replace(/-/g, "/")).getTime();
        if (nowTime >= toDate) {
          if (flag) {
            this.buttonText = "查看礼遇";
            this.buttonTip = "您已成功领取本次礼遇";
          } else {
            this.buttonText = "活动已结束";
            this.buttonTip = "期待您下次参与";
          }
        }
        this.showLoaded = false;
      }
    },
    formatDate(date) {
      let data =
        date && date.slice(0, 10).replace("-", "年").replace("-", "月") + "日";
      return data;
    },
    async handle(text) {
      if (text == "即刻申领") {
        this.trackGiftGet();
        let res = await this.getGiftStock2();
        if (res) {
          wx.redirectTo({
            // url: "/pages/customer/address?type=gift&id=" + this.activityId,
            url: `/pages/customer/address?type=gift&id=${this.activityId}&giftName=${this.giftInfo.giftName}`,
          });
					const pages = getCurrentPages();
					const currPage = pages[pages.length - 1];
					const route = currPage.route;
						const params = {
						page_name:"礼品详情",
						button_name: "即刻申领",
						gift_name: this.giftInfo?.giftName || '',
					};
					this.$commonSensors.giftsDetailTrack('GiftsDetailPageClick',params);
        } else {
          this.handleShowTextToast("礼遇已被领完，敬请期待下次活动。");
          this.getGiftStatus();
        }
      } else if (text == "查看礼遇") {
		
        this.isGetGiftTrue = true;
				const params = {
					page_name:"礼品详情",
					button_name: "查看礼遇",
					gift_name: this.giftInfo?.giftName || '',
				};
				this.$commonSensors.giftsDetailTrack('GiftsDetailPageClick',params);
        // uni.navigateTo({
        // 	url: '/pages/memberGift/applySuccess?recordId=' + this.recordId
        // })
      }
    },
    async handle2(text) {
		const params = {
			page_name:"礼品详情",
			button_name: "查看礼遇",
			gift_name: this.giftInfo?.giftName || '',
		};
	    this.$commonSensors.giftsDetailTrack('GiftsDetailPageClick',params);
      uni.navigateTo({
        url: "/pages/memberGift/applySuccess?recordId=" + this.recordId,
      });
    },

    trackGiftGet() {
      let eventName = "c_ebmp_treatment_gift_get";
      let trackParams = {
        c_gift_name: this.giftInfo.giftName,
      };
      getApp().commonClTrack(eventName, trackParams);
    },
    leftImg() {
      this.circular = false;
      let num = this.giftInfo.imgUrlDetail.length - 1;
      if (this.currentIndex <= 0) {
        this.currentIndex = num;
      } else {
        this.currentIndex--;
      }
    },
    rightImg() {
      this.circular = true;
      let num = this.giftInfo.imgUrlDetail.length - 1;
      if (this.currentIndex >= num) {
        this.currentIndex = 0;
      } else {
        this.currentIndex++;
      }
    },
  },
};
</script>

<style lang="scss">
page {
  height: 100%;
}

.gift-detail {
  height: 100%;
  overflow: auto;
  background: #fff;
  padding-bottom: 206rpx;

  &.fix-iphonex-button {
    padding-bottom: 60rpx;
  }

  .gift-container {
    .kv-box {
      width: 750rpx;
      height: 10;
    }

    .gift-info {
      font-size: 30rpx;
      line-height: 50rpx;
    }

    .gift-info,
    .activity_date,
    .gift-intro,
    .gift-notice {
      background: #fff;
      padding: 96rpx 48rpx 0rpx 48rpx;

      .title {
        font-family: NotoSansSC-Medium;
        font-size: 36rpx;
        line-height: 52rpx;
        text-transform: uppercase;
        letter-spacing: 0px;
        color: #000000;
        margin-bottom: 32rpx;
      }

      .text {
        font-family: FrankNew-Regular, NotoSansSC-Regular;
        font-size: 28rpx;
        font-weight: normal;
        line-height: 64rpx;
        text-align: justify;
        /* 浏览器可能不支持 */
        letter-spacing: 0;
        font-variation-settings: "opsz" auto;
        color: #000000;
      }
    }

    .gift-button {
      margin-top: 96rpx;

      .btn-tip {
        font-family: FrankNew-Regular, NotoSansSC-Regular;
        background: #fff;
        color: #000;
        font-size: 28rpx;
        padding-left: 48rpx;
        text-align: left;
        // line-height: 64px;
      }

      .btn-text {
        width: 654rpx;
        height: 80rpx;
        line-height: 80rpx;
        border-radius: 48rpx 16rpx 48rpx 48rpx;
        text-align: center;
        color: #ffffff;
        font-size: 28rpx;
        // padding: 34rpx 0;
        background: #000;
        text-transform: uppercase;
        letter-spacing: 0px;

        margin: 0 auto;

        &.grey {
          background: #c6c6c6;
          color: #757575;
        }
      }
    }
  }

  .mask-box-2 {
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    z-index: 99;
    background-color: rgba(0, 0, 0, 0.8);

    .params-padding-box-3 {
      position: relative;
      overflow: hidden;
      background: #ffffff;
      position: absolute;
      left: 48rpx;
      width: 654rpx;
      min-height: 728rpx;
    }
  }
}
</style>
